<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuth } from '@/composables/useAuth'
import { useTheme } from '@/composables/useTheme'
import {
  PhUser,
  PhEnvelope,
  PhPhone,
  PhMapPin,
  PhCalendar,
  PhPencil,
  PhCamera,
  PhCheck,
  PhX,
  PhUpload,
  PhGithubLogo,
  PhTwitterLogo,
  PhLinkedinLogo,
  PhGlobe,
} from '@phosphor-icons/vue'

defineOptions({
  name: 'ProfilePage',
})

/**
 * 用户认证和主题
 */
const { currentUser } = useAuth()
const { currentTheme } = useTheme()

/**
 * 编辑状态
 */
const isEditing = ref(false)
const isUploading = ref(false)

/**
 * 用户资料数据
 */
const userProfile = ref({
  name: '张三',
  email: 'zhangsan@example.com',
  phone: '+86 138 0013 8000',
  location: '北京市朝阳区',
  bio: '前端开发工程师，热爱技术分享和开源贡献。专注于 Vue.js、React 和现代前端技术栈的研究与实践。',
  joinDate: '2023-01-15',
  avatar:
    'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&h=400&fit=crop&crop=face',
  website: 'https://example.com',
  github: 'zhangsan',
  twitter: 'zhangsan_dev',
  linkedin: 'zhangsan',
  stats: {
    articles: 42,
    views: 15680,
    likes: 892,
    comments: 156,
  },
})

/**
 * 编辑表单数据
 */
const editForm = ref({ ...userProfile.value })

/**
 * 开始编辑
 */
const startEdit = (): void => {
  isEditing.value = true
  editForm.value = { ...userProfile.value }
}

/**
 * 取消编辑
 */
const cancelEdit = (): void => {
  isEditing.value = false
  editForm.value = { ...userProfile.value }
}

/**
 * 保存编辑
 */
const saveEdit = async (): Promise<void> => {
  try {
    // TODO: 调用API保存用户资料
    userProfile.value = { ...editForm.value }
    isEditing.value = false

    // 显示成功提示
    console.log('个人资料已更新')
  } catch (error) {
    console.error('保存失败:', error)
  }
}

/**
 * 上传头像
 */
const uploadAvatar = async (event: Event): Promise<void> => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  try {
    isUploading.value = true

    // TODO: 实现头像上传逻辑
    // 这里模拟上传过程
    await new Promise((resolve) => setTimeout(resolve, 2000))

    // 创建预览URL
    const previewUrl = URL.createObjectURL(file)
    if (isEditing.value) {
      editForm.value.avatar = previewUrl
    } else {
      userProfile.value.avatar = previewUrl
    }

    console.log('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
  } finally {
    isUploading.value = false
  }
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}

/**
 * 格式化数字
 */
const formatNumber = (num: number): string => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

/**
 * 当前显示的用户数据
 */
const displayUser = computed(() => {
  return isEditing.value ? editForm.value : userProfile.value
})

onMounted(() => {
  // 初始化页面数据
  console.log('个人资料页面已加载')
})
</script>

<template>
  <div class="profile-page min-h-screen bg-base-200/30">
    <!-- 页面头部 -->
    <div class="profile-header bg-gradient-to-r from-primary/10 to-secondary/10 pt-16 sm:pt-20">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl">
        <div class="profile-hero py-8 sm:py-12">
          <!-- 头像和基本信息 -->
          <div class="flex flex-col sm:flex-row items-center sm:items-start gap-6 sm:gap-8">
            <!-- 头像 -->
            <div class="profile-avatar relative group">
              <div class="avatar">
                <div
                  class="w-24 h-24 sm:w-32 sm:h-32 rounded-full ring ring-primary ring-offset-base-100 ring-offset-2"
                >
                  <img :src="displayUser.avatar" :alt="displayUser.name" class="object-cover" />
                </div>
              </div>

              <!-- 上传按钮 -->
              <label
                class="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
                :class="{ 'opacity-100': isUploading }"
              >
                <input
                  type="file"
                  accept="image/*"
                  class="hidden"
                  @change="uploadAvatar"
                  :disabled="isUploading"
                />
                <PhCamera v-if="!isUploading" :size="24" class="text-white" />
                <div v-else class="loading loading-spinner loading-md text-white"></div>
              </label>
            </div>

            <!-- 基本信息 -->
            <div class="flex-1 text-center sm:text-left">
              <div class="profile-info">
                <!-- 姓名和编辑按钮 -->
                <div class="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 mb-3">
                  <h1 v-if="!isEditing" class="text-2xl sm:text-3xl font-bold text-base-content">
                    {{ displayUser.name }}
                  </h1>
                  <input
                    v-else
                    v-model="editForm.name"
                    class="input input-bordered input-lg text-2xl sm:text-3xl font-bold bg-base-100 max-w-xs"
                    placeholder="输入姓名"
                  />

                  <!-- 编辑按钮组 -->
                  <div class="flex gap-2">
                    <button
                      v-if="!isEditing"
                      @click="startEdit"
                      class="btn btn-primary btn-sm gap-2"
                    >
                      <PhPencil :size="16" />
                      <span class="hidden sm:inline">编辑资料</span>
                    </button>
                    <div v-else class="flex gap-2">
                      <button @click="saveEdit" class="btn btn-success btn-sm gap-2">
                        <PhCheck :size="16" />
                        <span class="hidden sm:inline">保存</span>
                      </button>
                      <button @click="cancelEdit" class="btn btn-ghost btn-sm gap-2">
                        <PhX :size="16" />
                        <span class="hidden sm:inline">取消</span>
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 个人简介 -->
                <div class="mb-4">
                  <p
                    v-if="!isEditing"
                    class="text-base-content/80 text-sm sm:text-base leading-relaxed max-w-2xl"
                  >
                    {{ displayUser.bio }}
                  </p>
                  <textarea
                    v-else
                    v-model="editForm.bio"
                    class="textarea textarea-bordered w-full max-w-2xl bg-base-100"
                    rows="3"
                    placeholder="介绍一下自己..."
                  ></textarea>
                </div>

                <!-- 基本信息标签 -->
                <div
                  class="profile-tags flex flex-wrap gap-2 sm:gap-3 justify-center sm:justify-start"
                >
                  <div class="flex items-center gap-1 text-xs sm:text-sm text-base-content/60">
                    <PhCalendar :size="16" />
                    <span>{{ formatDate(displayUser.joinDate) }} 加入</span>
                  </div>
                  <div class="flex items-center gap-1 text-xs sm:text-sm text-base-content/60">
                    <PhMapPin :size="16" />
                    <span>{{ displayUser.location }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 统计数据 -->
          <div class="profile-stats mt-8">
            <div class="stats stats-horizontal bg-base-100 shadow-lg w-full">
              <div class="stat place-items-center">
                <div class="stat-title text-xs sm:text-sm">文章</div>
                <div class="stat-value text-lg sm:text-2xl text-primary">
                  {{ formatNumber(displayUser.stats.articles) }}
                </div>
              </div>
              <div class="stat place-items-center">
                <div class="stat-title text-xs sm:text-sm">阅读量</div>
                <div class="stat-value text-lg sm:text-2xl text-secondary">
                  {{ formatNumber(displayUser.stats.views) }}
                </div>
              </div>
              <div class="stat place-items-center">
                <div class="stat-title text-xs sm:text-sm">点赞</div>
                <div class="stat-value text-lg sm:text-2xl text-accent">
                  {{ formatNumber(displayUser.stats.likes) }}
                </div>
              </div>
              <div class="stat place-items-center">
                <div class="stat-title text-xs sm:text-sm">评论</div>
                <div class="stat-value text-lg sm:text-2xl text-info">
                  {{ formatNumber(displayUser.stats.comments) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细信息 -->
    <div class="profile-content">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl py-8 sm:py-12">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 sm:gap-8">
          <!-- 联系信息 -->
          <div class="lg:col-span-2">
            <div class="card bg-base-100 shadow-xl">
              <div class="card-body">
                <h2 class="card-title text-lg sm:text-xl mb-4 sm:mb-6">
                  <PhUser :size="24" />
                  联系信息
                </h2>

                <div class="space-y-4 sm:space-y-6">
                  <!-- 邮箱 -->
                  <div class="contact-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhEnvelope :size="16" />
                        邮箱地址
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.email"
                      type="email"
                      class="input input-bordered w-full bg-base-100"
                      placeholder="输入邮箱地址"
                    />
                    <div v-else class="text-base-content/80">{{ displayUser.email }}</div>
                  </div>

                  <!-- 手机号 -->
                  <div class="contact-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhPhone :size="16" />
                        手机号码
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.phone"
                      type="tel"
                      class="input input-bordered w-full bg-base-100"
                      placeholder="输入手机号码"
                    />
                    <div v-else class="text-base-content/80">{{ displayUser.phone }}</div>
                  </div>

                  <!-- 地址 -->
                  <div class="contact-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhMapPin :size="16" />
                        所在地区
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.location"
                      class="input input-bordered w-full bg-base-100"
                      placeholder="输入所在地区"
                    />
                    <div v-else class="text-base-content/80">{{ displayUser.location }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 社交链接 -->
          <div class="lg:col-span-1">
            <div class="card bg-base-100 shadow-xl">
              <div class="card-body">
                <h2 class="card-title text-lg sm:text-xl mb-4 sm:mb-6">
                  <PhGlobe :size="24" />
                  社交链接
                </h2>

                <div class="space-y-4">
                  <!-- 个人网站 -->
                  <div class="social-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhGlobe :size="16" />
                        个人网站
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.website"
                      type="url"
                      class="input input-bordered input-sm w-full bg-base-100"
                      placeholder="https://example.com"
                    />
                    <a
                      v-else-if="displayUser.website"
                      :href="displayUser.website"
                      target="_blank"
                      class="link link-primary text-sm break-all"
                    >
                      {{ displayUser.website }}
                    </a>
                    <span v-else class="text-base-content/50 text-sm">未设置</span>
                  </div>

                  <!-- GitHub -->
                  <div class="social-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhGithubLogo :size="16" />
                        GitHub
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.github"
                      class="input input-bordered input-sm w-full bg-base-100"
                      placeholder="用户名"
                    />
                    <a
                      v-else-if="displayUser.github"
                      :href="`https://github.com/${displayUser.github}`"
                      target="_blank"
                      class="link link-primary text-sm"
                    >
                      @{{ displayUser.github }}
                    </a>
                    <span v-else class="text-base-content/50 text-sm">未设置</span>
                  </div>

                  <!-- Twitter -->
                  <div class="social-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhTwitterLogo :size="16" />
                        Twitter
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.twitter"
                      class="input input-bordered input-sm w-full bg-base-100"
                      placeholder="用户名"
                    />
                    <a
                      v-else-if="displayUser.twitter"
                      :href="`https://twitter.com/${displayUser.twitter}`"
                      target="_blank"
                      class="link link-primary text-sm"
                    >
                      @{{ displayUser.twitter }}
                    </a>
                    <span v-else class="text-base-content/50 text-sm">未设置</span>
                  </div>

                  <!-- LinkedIn -->
                  <div class="social-item">
                    <label class="label">
                      <span class="label-text flex items-center gap-2">
                        <PhLinkedinLogo :size="16" />
                        LinkedIn
                      </span>
                    </label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.linkedin"
                      class="input input-bordered input-sm w-full bg-base-100"
                      placeholder="用户名"
                    />
                    <a
                      v-else-if="displayUser.linkedin"
                      :href="`https://linkedin.com/in/${displayUser.linkedin}`"
                      target="_blank"
                      class="link link-primary text-sm"
                    >
                      @{{ displayUser.linkedin }}
                    </a>
                    <span v-else class="text-base-content/50 text-sm">未设置</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 个人资料页面样式 */
.profile-page {
  min-height: 100vh;
}

.profile-header {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, hsl(var(--p) / 0.1) 0%, hsl(var(--s) / 0.1) 100%);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
  }

  .profile-hero {
    position: relative;
    z-index: 1;
  }
}

.profile-avatar {
  .avatar {
    transition: transform 0.3s ease;
  }

  &:hover .avatar {
    transform: scale(1.05);
  }
}

.profile-stats {
  .stats {
    border-radius: 1rem;
    overflow: hidden;

    .stat {
      padding: 1rem;

      @media (max-width: 640px) {
        padding: 0.75rem 0.5rem;
      }
    }
  }
}

.contact-item,
.social-item {
  .label {
    margin-bottom: 0.5rem;

    .label-text {
      font-weight: 500;
      color: hsl(var(--bc) / 0.8);
    }
  }

  .input {
    transition: all 0.2s ease;

    &:focus {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px hsl(var(--p) / 0.15);
    }
  }
}

/* 响应式设计 */
@media (max-width: 640px) {
  .profile-header {
    padding-top: 4rem;
  }

  .profile-hero {
    padding: 2rem 0;
  }

  .profile-info {
    .flex {
      flex-direction: column;
      align-items: center;
      gap: 0.75rem;
    }
  }

  .profile-tags {
    justify-content: center;
    gap: 0.5rem;

    > div {
      font-size: 0.75rem;
    }
  }

  .card-body {
    padding: 1.5rem;
  }

  .card-title {
    font-size: 1.125rem;
    margin-bottom: 1rem;
  }

  .space-y-4 > * + * {
    margin-top: 1rem;
  }
}

/* 动画效果 */
.profile-avatar {
  animation: fadeInUp 0.6s ease-out;
}

.profile-info {
  animation: fadeInUp 0.6s ease-out 0.1s both;
}

.profile-stats {
  animation: fadeInUp 0.6s ease-out 0.2s both;
}

.card {
  animation: fadeInUp 0.6s ease-out 0.3s both;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态 */
.loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
